package lock

import (
	"fmt"
	"sync"
	"time"
)

var (
	num    int64
	wg     sync.WaitGroup
	rwlock sync.RWMutex
)

func write() {
	//加写锁
	rwlock.Lock()
	num = num + 1
	//模拟真实写数据消耗的时间
	time.Sleep(10 * time.Millisecond)
	//解写锁
	rwlock.Unlock()
	wg.Done()
}

func read() {
	//加读锁
	rwlock.RLock()
	//模拟真实读取数据消耗时间
	time.Sleep(time.Millisecond)
	//解读锁
	rwlock.RUnlock()
	//退出携程前记录-1
	wg.Done()
}

func RWLock() {
	start := time.Now()

	for i := 0; i < 50; i++ {
		wg.Add(1)
		go write()
	}

	for i := 0; i < 10000; i++ {
		wg.Add(1)
		go read()
	}

	wg.Wait()
	fmt.Println(time.Since(start))
}
